<?php

namespace App\Http\Controllers\Admin;

use App\Models\AnswerActivity;
use App\Models\AnswerActivityProblem;
use App\Models\AnswerActivityProblemAnswer;
use App\Models\AnswerActivityUserAnswerRecord;
use App\Models\AnswerActivityUserCorrectAnswerRecord;
use App\Models\AnswerActivityUserStairsAnswerRecord;
use App\Validate\AnswerActivityProblemValidate;
use Illuminate\Support\Facades\DB;

/**
 * 获取题目管理
 */
class AnswerActivityProblemController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityProblem();
        $this->validate = new AnswerActivityProblemValidate();
    }

    /**
     * 列表
     * @param act_id int 活动id
     * @param unit_id int 单位id  
     * @param state int 1正常 2被禁用
     * @param is_show_analysis int 是否显示解析  1、显示 2、不显示
     * @param page int 当前页
     * @param limit int 分页大小
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     * @param keywords string 搜索关键词(类型题目)
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $keywords = $this->request->keywords;
        $unit_id = $this->request->unit_id;
        $state = $this->request->state;
        $is_show_analysis = $this->request->is_show_analysis;
        $act_id = $this->request->act_id;

        $res = $this->model->lists($act_id, $keywords, $unit_id, $state, $is_show_analysis, $start_time, $end_time, $page, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        $res['node'] = AnswerActivity::where('id', $this->request->act_id)->value('node');
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['unit_name'] = !empty($val['con_unit']['name']) ?  $val['con_unit']['name'] : config('other.unit_name');
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

            unset($res['data'][$key]['con_unit']);
        }

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param act_id int活动id     必传
     * @param unit_id int单位id  区域联盟、单位联盟 可选   独立活动不要此参数
     * @param title string 题目   最多 150个字符    必传
     * @param img string 图片
     * @param type string 题目类型  1 选择 （默认）2 填空题    必传  
     * @param analysis string 解析  最多 200个字符   首次添加，有解析就显示，无解析就不显示
     * @param answer string 答案  json 格式   填空题 只允许有一个答案，选择题至少 2个答案，最多10个答案    必传
     * 
     * json 格式数据  [{"content":1,"status":1},{"content":1,"status":2},{"content":1,"status":2}]   
     * 数组 格式数据  [['content'=>1 , 'status'=>1] , [content'=>1 ,'status'=>2] , ['content'=>1 , 'status'=>3]]
     * 
     * status 答题状态  1代表正确  2代表错误  默认2     如果是填空题，status参数无效，固定是 1
     * content 答案内容
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        if (!empty($this->request->analysis) && mb_strlen($this->request->analysis) > 200) {
            return $this->returnApi(202, '解析最多200字');
        }

        //是否必传区域id
        $node = AnswerActivity::where('id', $this->request->act_id)->value('node');
        if ($node == 1 && !empty($this->request->unit_id)) {
            return $this->returnApi(202, '此活动为独立活动，不能选择所属单位');
        }

        $condition[] = ['act_id', '=', $this->request->act_id];
        $is_exists = $this->model->nameIsExists($this->request->title, 'title', null, 1, $condition);
        if ($is_exists) {
            return $this->returnApi(202, "该题目已存在");
        }
        $answer = json_decode($this->request->answer, true);
        if ($this->request->type == 1 && (count($answer) < 2 || count($answer) > 10)) {
            return $this->returnApi(202, "选择题的答案最少2个，最多10个!");
        }
        if ($this->request->type == 2 && count($answer) != 1) {
            return $this->returnApi(202, "填空题的答案只能存在一个！");
        }
        DB::beginTransaction();
        try {
            $data = $this->request->all();
            $data['is_show_analysis'] = empty($this->request->analysis) ? 2 : 1;
            $data['unit_id'] = $this->request->unit_id ?: 0;
            unset($data['answer']);
            $this->model->add($data);

            //添加答案
            $activityProblemAnswerModel = new AnswerActivityProblemAnswer();
            $answer_id = $activityProblemAnswerModel->add($answer, $this->model->id, $this->request->type);

            $this->model->answer_id = $answer_id; //修改正确答案id
            $this->model->save();

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 修改
     * @param id int 标题id     必传
     * @param unit_id int单位id  区域联盟、单位联盟 可选   独立活动不要此参数
     * @param title string 题目   最多 150个字符    必传
     * @param img string 图片
     * @param type string 题目类型  1 选择 （默认）2 填空题    不允许修改  
     * @param analysis string 解析  最多 200个字符   首次添加，有解析就显示，无解析就不显示
     * @param answer string 答案  json 格式   填空题 只允许有一个答案，选择题至少 2个答案，最多10个答案    必传
     * 
     * 不能修改答案的个数
     * json 格式数据  [{"id":1,"content":1,"status":1},{"id":2,"content":1,"status":2},{"id":3,"content":1,"status":2}]   答题状态  1代表正确  2代表错误  默认2
     * 数组 格式数据  [['id'=>1 ,'content'=>1 , 'status'=>1] , ['id'=>2 , 'content'=>1 ,'status'=>2] , ['id'=>3 ,'content'=>1 , 'status'=>3]]
     * status 答题状态  1代表正确  2代表错误  默认2     如果是填空题，status参数无效，固定是 1
     * content 答案内容
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $result = $this->model->where('id', $this->request->id)->first();
        if (empty($result)) {
            return $this->returnApi(201, "参数传递错误");
        }

        //是否必传区域id
        $node = AnswerActivity::where('id', $this->request->act_id)->value('node');
        if ($node == 1 && !empty($this->request->unit_id)) {
            return $this->returnApi(202, '此活动为独立活动，不能选择所属单位');
        }

        $condition[] = ['act_id', '=', $this->request->act_id];
        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id, 1, $condition);
        if ($is_exists) {
            return $this->returnApi(202, "该题目已存在");
        }
        $answer = json_decode($this->request->answer, true);
        if ($this->request->type == 1 && (count($answer) < 2 || count($answer) > 10)) {
            return $this->returnApi(202, "选择题的答案最少2个，最多10个!");
        }
        if ($this->request->type == 2 && count($answer) != 1) {
            return $this->returnApi(202, "填空题的答案只能存在一个！");
        }

        DB::beginTransaction();
        try {
            $data = $this->request->all();
            $data['unit_id'] = $this->request->unit_id ?: 0;
            unset($data['answer']);
            unset($data['type']);
            $this->model->change($data);

            //添加答案
            $activityProblemAnswerModel = new AnswerActivityProblemAnswer();
            $answer_id = $activityProblemAnswerModel->change($answer, $this->request->id, $this->request->type);

            $result->answer_id = $answer_id; //修改正确答案id
            $result->save();

            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除单个题目
     * @param id int id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //判断是否有人答题
        $activityUserAnswerRecordModel = new AnswerActivityUserAnswerRecord();
        $activityUserStairsAnswerRecordModel = new AnswerActivityUserStairsAnswerRecord();
        $activityUserCorrectAnswerRecordModel = new AnswerActivityUserCorrectAnswerRecord();

        $isBeenProblem1 = $activityUserAnswerRecordModel->isBeenProblem($this->request->id);
        $isBeenProblem2 = $activityUserStairsAnswerRecordModel->isBeenProblem($this->request->id);
        $isBeenProblem3 = $activityUserCorrectAnswerRecordModel->isBeenProblem($this->request->id);

        if ($isBeenProblem1 || $isBeenProblem2 || $isBeenProblem3) {
            return $this->returnApi(202, "此问题已有用户参与，不允许删除");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 删除多个问题
     * @param act_id int 活动id 
     * @param ids int id all 表示全部   多个 逗号拼接
     */
    public function delMany()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del_many')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        DB::beginTransaction();
        try {
            $this->model->delMany($this->request->act_id, $this->request->ids);

            DB::commit();
            return $this->returnApi(200, "删除成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 禁用与启用
     * @param act_id int 活动id 
     * @param ids int 问题id  多都逗号拼接    all 表示全部
     * @param state int 状态 1正常 2被禁用
     */
    public function disablingAndEnabling()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('disabling_and_enabling')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            $condition[] = ['act_id', '=', $this->request->act_id];

            list($code, $msg) = $this->model->resumeAndCancel($this->request->ids, 'state', $this->request->state , 1 , $condition);

            $state = $this->request->state == 1 ? '启用' : '禁用';

            DB::commit();
            return $this->returnApi($code, $state . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 显示与隐藏解析
     * @param act_id int 活动id 
     * @param ids int 问题id  多都逗号拼接    all 表示全部
     * @param is_show_analysis int 是否显示解析  1、显示 2、不显示
     */
    public function analysisShowAndHidden()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('analysis_show_and_hidden')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            $condition[] = ['act_id', '=', $this->request->act_id];

            list($code, $msg) = $this->model->resumeAndCancel($this->request->ids, 'is_show_analysis', $this->request->is_show_analysis , 1 , $condition);

            $is_show_analysis = $this->request->is_show_analysis == 1 ? '显示解析' : '隐藏解析';

            DB::commit();
            return $this->returnApi($code, $is_show_analysis . $msg, $code === 200 ? true : false);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
